<template>
  <a-drawer :title="title" style="height: 100%" :width="700" :closable="true" :mask="false"
    :wrap-style="{ position: 'absolute' }" placement="left" :visible="visible"
    wrapClassName="sk-left-drawer task_add_drawer" getContainer=".skpz" @close="close">
    <div v-if="isAddStatus" class="ctr" style="position: sticky; top: 0; margin-top: -24px; z-index: 2;">
      <div :class="{ 'has-error': errorTaskName }">
        <label>任务名称：</label>
        <a-input v-model="editForm.taskName" placeholder="请输入任务名称" @blur="setTaskName" />
      </div>
      <a-button type="primary" class="btn" @click="onAdd('add')">输入轨迹点</a-button>
      <a-tooltip placement="topRight">
        <template slot="title">
          <span>支持直接点击地图进行位置打点</span>
        </template>
        <a-icon type="exclamation-circle" :style="{ color: '#ccc', fontSize: '24px', margin: '5px 0 0 8px' }" />
      </a-tooltip>
    </div>
    <div class="skpz-table">
      <a-table class="sk-add-table" :columns="listObject.columns" :loading="listLoading" :dataSource="listObject.list"
        :pagination="false">
        <span slot="order" slot-scope="text, record, index">{{ index + 1 }}</span>
        <template v-for="col in ['longitude', 'latitude', 'range']" :slot="col" slot-scope="text, record">
          <div :key="col">
            <template v-if="col === 'range'">
              <a-range-picker v-model="rangeTime[record.key]" v-if="record.editable" :defaultValue="
                record.elapsedStartTime
                  ? [
                    moment(record.elapsedStartTime, 'YYYY-MM-DD HH:mm:ss'),
                    moment(record.elapsedEndTime, 'YYYY-MM-DD HH:mm:ss')
                  ]
                  : null
              " :showTime="{
  hideDisabledOptions: true,
  defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('11:59:59', 'HH:mm:ss')]
}" format="YYYY-MM-DD HH:mm:ss" style="width: 330px;" @openChange="openChange()"
                @change="(date, dateString) => changeRange(date, dateString, record.key)" />
              <span v-else-if="record.elapsedStartTime && record.elapsedEndTime">{{ record.elapsedStartTime |
                  dateTimeFormat
              }} ~ {{ record.elapsedEndTime | dateTimeFormat }}</span>
            </template>
            <a-input v-else-if="record.editable && record.type === 'add'" style="margin: -5px 0" :value="text"
              @change="e => handleChange(e.target.value, record.key, col)" />
            <template v-else>{{ text }}</template>
          </div>
        </template>
        <template slot="action" slot-scope="text, record, index" v-if="isAddStatus">
          <div class="editable-row-operations">
            <span v-if="record.editable">
              <a href="javascript:;" @click="onSave(record.key, index)">保存</a>
              <a href="javascript:;" class="font-gray" style="margin-left: 12px;" @click="onCancel(record.key)">取消</a>
            </span>
            <span v-else>
              <a href="javascript:;" @click="onEdit(record.key)">编辑</a>
              <a href="javascript:;" @click="onCopy(record.key)" style="margin: 0 12px;">复制</a>
              <a-popconfirm title="确定删除该轨迹吗?" @confirm="onDelete(record.key)">
                <a href="javascript:;" class="font-red">删除</a>
              </a-popconfirm>
            </span>
          </div>
        </template>
      </a-table>
    </div>
    <!-- position: 'absolute',
          bottom: 0, -->
    <div :style="{
      width: '100%',
      borderTop: '1px solid #E8E8E8',
      padding: '10px 16px',
      textAlign: 'right',
    }">
      <a-button v-if="!isAddStatus && isOperation" type="primary" class="sure"
        :style="{ marginRight: '8px', 'background-color': 'rgba(24,76,151,1);', 'border-color': 'rgba(24,76,151,1);' }"
        @click="copyAndAdd">复制轨迹点创建任务</a-button>
      <a-button :style="{ marginRight: '8px' }" @click="cancel">取消</a-button>
      <a-button v-if="isAddStatus" type="primary" :loading="loading" @click="onSubmit" class="sure"
        :style="{ 'background-color': 'rgba(24,76,151,1);', 'border-color': 'rgba(24,76,151,1);' }">确认</a-button>
    </div>
  </a-drawer>
</template>

<script>
import moment from 'moment'
import { trim, testFloat } from '@/libs/tools'
import { convertDateFromString } from '@/libs/util'
import * as api from '@/api/wxSmuggle/eventModel.js'
export default {
  props: ['isAdd', 'addPoint', 'title', 'visible'],
  data() {
    return {
      listObject: {
        list: [],
        columns: []
      },
      columns1: [
        {
          title: '序号',
          dataIndex: 'order',
          width: 50,
          align: 'center',
          scopedSlots: { customRender: 'order' }
        },
        {
          title: '经度',
          dataIndex: 'longitude',
          width: 90,
          align: 'center',
          scopedSlots: { customRender: 'longitude' }
        },
        {
          title: '纬度',
          dataIndex: 'latitude',
          width: 90,
          align: 'center',
          scopedSlots: { customRender: 'latitude' }
        },
        {
          title: '时间',
          dataIndex: 'range',
          width: 120,
          align: 'center',
          scopedSlots: { customRender: 'range' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 130,
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      columns2: [
        {
          title: '序号',
          dataIndex: 'order',
          width: 50,
          align: 'center',
          scopedSlots: { customRender: 'order' }
        },
        {
          title: '经度',
          dataIndex: 'longitude',
          width: 90,
          align: 'center',
          scopedSlots: { customRender: 'longitude' }
        },
        {
          title: '纬度',
          dataIndex: 'latitude',
          width: 90,
          align: 'center',
          scopedSlots: { customRender: 'latitude' }
        },
        {
          title: '时间',
          dataIndex: 'range',
          align: 'center',
          width: 300,
          scopedSlots: { customRender: 'range' }
        }
      ],
      editForm: {},
      cacheData: [],
      count: 0,
      errorTaskName: false,
      errorTxt: '',
      loading: false,
      listLoading: false,
      isAddStatus: true,
      taskId: '',
      isOperation: true,
      rangeTime: {},
      recordKey: 0,
      isClearTime: false
    }
  },
  mounted() {
    this.cacheData = this.listObject.list.map(item => ({ ...item }))
  },
  watch: {
    addPoint(data) {
      this.onAdd('click', data)
      this.$emit('on-change-point', this.listObject.list, 'red', this.count)
    },
    'editForm.taskName'(value) {
      this.errorTaskName = !value
    },
    isAdd(value) {
      console.log('value:' + value)
      this.isAddStatus = value
      //详情的情况
      if (value) {
        //新增
        this.listObject.columns = this.columns1
      } else {
        //详情
        this.listObject.columns = this.columns2
      }
    }
  },
  methods: {
    moment,
    setOperation(val) {
      this.isOperation = val
    },
    getData(id) {
      this.taskId = id
      this.getDetail()
    },
    //关闭，缩进
    close() {
      this.loading = false
      this.$emit('close')
    },
    //取消，回到任务列表
    cancel() {
      this.rangeTime = {}
      this.loading = false
      this.listObject.list = []
      this.editForm = {}
      this.errorTaskName = false
      this.$emit('cancel')
    },
    copyAndAdd() {
      //编辑模式
      this.listObject.list.forEach(item => {
        item.type = 'add'
        item.editable = true
      })
      this.$emit('copyAndAdd') //切换到创建模式
    },
    onAdd(type, data) {
      this.count += 1
      const newData = {
        editable: true,
        type: type,
        key: this.count,
        longitude: (data && data.longitude) || '',
        latitude: (data && data.latitude) || '',
        elapsedStartTime: '',
        elapsedEndTime: ''
      }
      this.listObject.list = [...this.listObject.list, newData]
      this.cacheData = this.listObject.list.map(item => ({ ...item }))
    },
    onDelete(key) {
      const dataSource = [...this.listObject.list]
      this.listObject.list = dataSource.filter(item => item.key !== key)
      this.$emit('on-change-point', this.listObject.list, 'red', key)
    },
    onEdit(key) {
      const newData = [...this.listObject.list]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        target.editable = true
        this.listObject.list = newData
      }
    },
    onSave(key, index) {
      let _this = this
      const newData = [...this.listObject.list]
      console.log('newData')
      console.log(newData, key, index)
      let flag = true
      if (newData.length > 0) {
        if (newData[index].latitude == '' || newData[index].longitude == '') {
          this.$message.warning('经纬度不能为空')
          flag = false
          return
        }
        if (newData[index].elapsedStartTime == '' || newData[index].elapsedEndTime == '') {
          this.$message.warning('时间不能为空')
          flag = false
          return
        }
      }
      if (flag) {
        const target = newData.filter(item => key === item.key)[0]
        if (target) {
          if (this.millionSecondToHour(target.elapsedEndTime, target.elapsedStartTime) > 1) {
            this.$confirm({
              title: `当前添加数据时间前后时间差大于一小时，可能会导致数据量过于庞大，确定保存？`,
              // content: '你确定要删除这项告警配置吗？',
              okText: '确定',
              cancelText: '取消',
              onOk() {
                delete target.editable
                _this.listObject.list = newData
                _this.cacheData = newData.map(item => ({ ...item }))
              },
              onCancel() { }
            })
          } else {
            delete target.editable
            _this.listObject.list = newData
            _this.cacheData = newData.map(item => ({ ...item }))
          }
        }
        // 比较开始结束时间排序
        // this.sortList()
        this.$emit('on-change-point', this.listObject.list, 'red', key)
      }
    },
    getDetail() {
      this.listLoading = true
      api
        .getTimeSpaceCollisionTaskResult({ taskId: this.taskId })
        .then(res => {
          if (res.success) {
            this.listLoading = false
            let trackList = res.result.standardTrackList
            if (trackList.length > 0) {
              this.listObject.list = []
              trackList.forEach((item, index) => {
                this.listObject.list.push({
                  key: index,
                  longitude: item.longitude,
                  latitude: item.latitude,
                  elapsedStartTime: item.elapsedStartTime,
                  elapsedEndTime: item.elapsedEndTime
                })
              })
              this.count = 0
              //不可编辑模式
              this.listObject.list.forEach(item => {
                item.type = 'view'
                item.editable = false
                this.count += 1
              })
              let arr = [
                {
                  list: this.listObject.list
                }
              ]
              // 绘制轨迹
              this.$emit('on-task-details-drawer', arr)
              this.editForm.copyFrom = this.taskId  //复制轨迹点创建任务,提交参数带上任务id，用于审计日志区分
            }

            // this.$refs.table.onClearRowKeys()
          } else {
            this.listLoading = false
          }
        })
        .catch(e => {
          this.listLoading = false
          this.$message.warn('请求失败！')
        })
      // let arr = [
      //   {
      //     list: [
      //       { key: 0, longitude: '125.177238', latitude: '43.974533' },
      //       { key: 1, longitude: '125.209433', latitude: '43.819878' }
      //     ]
      //   }
      // ]

      // 绘制轨迹
      // this.$emit('on-task-details-drawer', arr)
    },
    onCopy(key) {
      const target = this.listObject.list.filter(item => key === item.key)[0]
      this.onAdd('click', target)
      this.$emit('on-change-point', this.listObject.list, 'red', this.count)
    },
    onCancel(key) {
      const dataSource = [...this.listObject.list]
      this.listObject.list = dataSource.filter(item => item.key !== key)
      this.$emit('on-change-point', this.listObject.list, 'red', key)
      // const newData = [...this.listObject.list]
      // const target = newData.filter(item => key === item.key)[0]
      // if (target) {
      //   Object.assign(target, this.cacheData.filter(item => key === item.key)[0])
      //   target.editable = false
      //   this.listObject.list = newData
      // }
    },
    sortList() {
      const newData = [...this.listObject.list]
      let partList = newData.filter(item => {
        if (item.elapsedStartTime && item.elapsedEndTime) {
          return item
        }
      })
      partList.sort((a, b) => {
        if (+new Date(a.elapsedStartTime) - +new Date(b.elapsedStartTime) === 0) {
          return +new Date(a.elapsedEndTime) - +new Date(b.elapsedEndTime)
        } else {
          return +new Date(a.elapsedStartTime) - +new Date(b.elapsedStartTime)
        }
      })
      this.listObject.list = [...new Set([...partList, ...newData])]
    },
    openChange() {
      //超过一小时，关闭窗口就清空对应的时间控件
      if (this.isClearTime) {
        this.rangeTime[this.recordKey] = undefined
      }
    },
    changeRange(date, dateString, key) {
      this.recordKey = key
      // console.log("key")
      // console.log(key)
      let t1 = new Date(dateString[0]);
      let t2 = new Date(dateString[1]);
      let s = (t2.getTime() - t1.getTime());//毫秒
      s = (s / (1000 * 60 * 60));
      // console.log("时间跨度：")
      // console.log(s)
      if (s > 1) {
        this.$message.warning("时间跨度不能超过1小时！")
        this.isClearTime = true
      } else {
        this.isClearTime = false
        this.handleChange(dateString[0], key, 'elapsedStartTime')
        this.handleChange(dateString[1], key, 'elapsedEndTime')
      }

      // this.handleChange(convertDateFromString(dateString[0], 'yyyy-MM-dd'), key, 'elapsedStartTime')
      // this.handleChange(convertDateFromString(dateString[1], 'yyyy-MM-dd'), key, 'elapsedEndTime')
    },
    handleChange(value, key, column) {
      // console.log('value')
      // console.log(value)
      const newData = [...this.listObject.list]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        // 经纬度输入收尾去空格
        if (typeof value === 'string') {
          value = trim(value)
        }
        target[column] = value
        this.listObject.list = newData
      }
    },
    setTaskName() {
      this.editForm.taskName = trim(this.editForm.taskName)
    },
    onSubmit() {
      // 先进行时间排序
      // this.sortList()
      this.editForm.incidentTaskId = this.$route.query.taskId
      if (!this.editForm.taskName) {
        this.errorTaskName = true
        this.$message.error('任务名称未填写！')
      } else if (this.isAccord(this.listObject.list)) {
        this.$message.error(this.errorTxt)
      } else {
        let _this = this
        const newData = [...this.listObject.list]
        let partList = newData.filter(item => {
          if (item.elapsedStartTime && item.elapsedEndTime) {
            return item
          }
        })
        let pass = true
        let passIndex = []
        partList.forEach((e, index) => {
          if (this.millionSecondToHour(e.elapsedEndTime, e.elapsedStartTime) > 1) {
            pass = false
            passIndex.push(index + 1)
          }
        })
        if (!pass) {
          this.$confirm({
            title: `您添加的第${passIndex.join(',第')}数据前后时间差大于一小时，可能会导致数据量过于庞大，确定提交？`,
            // content: '你确定要删除这项告警配置吗？',
            okText: '确定',
            cancelText: '取消',
            onOk() {
              _this.sortList()
              _this.editForm.trackList = _this.listObject.list.map(
                ({ longitude, latitude, elapsedStartTime, elapsedEndTime }) => {
                  return {
                    longitude: parseFloat(longitude),
                    latitude: parseFloat(latitude),
                    elapsedStartTime,
                    elapsedEndTime
                  }
                }
              )
              _this.loading = true
              api
                .saveTimeSpaceCollisionTask(_this.editForm)
                .then(res => {
                  if (res.success) {
                    _this.$message.success('增加查询轨迹成功！')
                    this.rangeTime = {}
                    _this.close()
                    _this.loading = false
                    _this.$emit('on-submit-success')
                  } else {
                    _this.loading = false
                    _this.$message.warning(res.message)
                  }
                })
                .catch(() => {
                  _this.loading = false
                  _this.$message.warning(res.message)
                })
            },
            onCancel() { }
          })
        } else {
          this.sortList()
          this.editForm.trackList = this.listObject.list.map(
            ({ longitude, latitude, elapsedStartTime, elapsedEndTime }) => {
              return {
                longitude: parseFloat(longitude),
                latitude: parseFloat(latitude),
                elapsedStartTime,
                elapsedEndTime
              }
            }
          )
          this.loading = true
          api
            .saveTimeSpaceCollisionTask(this.editForm)
            .then(res => {
              if (res.success) {
                this.$message.success('增加查询轨迹成功！')
                this.rangeTime = {}
                this.close()
                this.loading = false
                this.$emit('on-submit-success')
              } else {
                _this.loading = false
                _this.$message.warning(res.message)
              }
            })
            .catch(() => {
              this.loading = false
              _this.$message.warning(res.message)
            })
        }
      }
    },
    millionSecondToHour(endTime, startTime) {
      let millionSecond = endTime - startTime
      return millionSecond / (1000 * 60 * 60)
    },
    isAccord(list) {
      let flag = false
      this.errorTxt = '第'
      list.forEach((item, index) => {
        if (testFloat(item.longitude) || testFloat(item.latitude) || !item.elapsedStartTime || !item.elapsedEndTime) {
          this.errorTxt += `${index + 1}、`
          flag = true
          item.editable = true
        } else {
          item.editable = false
        }
      })
      this.errorTxt = this.errorTxt.replace(/、$/, '')
      this.errorTxt += '条输入不符合！'
      this.$forceUpdate()
      return flag
    }
  }
}
</script>

<style lang="less">
.task_add_drawer {
  .ant-drawer-content-wrapper {
    // background: rgba(0, 0, 0, 0.4);
    position: absolute;
    top: 0;
    bottom: 0;
    height: auto;
  }

  .ant-drawer-content {
    // background: rgba(0, 0, 0, 0.4);
  }

  .ant-drawer-header {
    // background: rgba(0, 0, 0, 0.4);
    border: none;

    .ant-drawer-title {
      color: red !important;
      // color: #fff;
    }
  }

  .ant-drawer-body {
    padding: 20px 0;

    .add-box {
      padding: 0px 20px 24px;

      button {
        // background: rgba(24, 76, 151, 1);
        // border: rgba(24, 76, 151, 1);
        height: 40px;
      }

      .search {
        width: 200px;
        height: 40px;
        float: right;

        .ant-input-suffix {
          display: inline-block;
          width: 40px;
          height: 40px;
          // background: rgba(24, 76, 151, 1);
          right: 0;
          border-radius: 0 3px 3px 0;

          i {
            font-size: 20px;
            color: #fff;
            margin-left: 50%;
            margin-top: 50%;
            transform: translate(-50%, -50%);
          }
        }
      }
    }
  }

  .sk-add-table {

    .ant-table-thead>tr>th,
    .ant-table-tbody>tr>td {
      padding: 15px 8px;
    }
  }

  .ctr {
    display: flex;
    background-color: transparent;
    // color: #fff;
    padding: 20px 30px;

    input {
      width: 250px;
    }

    button {
      // line-height: 40px;
      // background-color: rgba(24, 76, 151, 1);
      // border-color: rgba(24, 76, 151, 1);
      margin-left: 50px;
    }
  }

  .sk-add-table {
    input {
      background: transparent;
      // color: #fff;
    }

    span {
      // color: #fff;
    }

    .editable-row-operations {
      a {
        // color: #fff;
      }
    }

    .ant-calendar-picker-input {
      background: transparent;
    }
  }
}
</style>
